<template>
  <div class="table-gl-w">
    <a-tabs @change="changeStatus" v-model:active-key="currentTab" size="mini">
      <a-tab-pane v-for="tab in tabsList" :key="tab.key">
        <template #title>
          <span>{{ tab.title }}</span>
          <span v-if="tab.key">({{ countMap[tab.key] || 0 }})</span>
        </template>
      </a-tab-pane>
    </a-tabs>
    <div class="search-w table-filter-form">
      <FilterTable :filterItem="filterItem" :isReset="true" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="getTableList">
        <template #headerLeft>
          <a-space>
            <a-checkbox v-model="isCheckedAll" @change="changeCheckedAll">全选</a-checkbox>
            <a-button class="gray-outline" size="medium" @click="openStopDialog" v-if="currentTab == 30 && $authPass('procurement.plan.cutoff')">终止申购</a-button>
            <a-button class="gray-outline" size="medium" @click="openSetLabel(checkedList)" v-if="currentTab == 30 && $authPass('procurement.plan.set.label')">批量设置标签</a-button>
          </a-space>
        </template>
        <template #tableBody>
          <a-empty v-if="!tableList.length && !tableLoading" />
          <a-spin v-else :loading="tableLoading" style="width: 100%; height: 100%">
            <a-scrollbar style="height: 100%; overflow: auto">
              <ul class="order-item-wrap">
                <li class="order-item-w" v-for="(item, i) in tableList" :key="i">
                  <ApplicationItem :key="i" :detail="item" @changeChecked="changeChecked" source="demanderItem" :labelAuth="$authPass('procurement.plan.set.label')" @update="getTableList" />
                </li>
              </ul>
            </a-scrollbar>
          </a-spin>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.pageNum" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
  <!-- 终止申购 -->
  <StopApplicationOrder v-if="showStopDialog" :isShow="showStopDialog" :list="checkedList" @closed="showStopDialog = false" @success="getListAndCount" />
  <!-- 设置标签 -->
  <SetPurchaseLabel v-if="showSetLabel" :isShow="showSetLabel" source="application" :list="currentList" @closed="showSetLabel = false" @success="getListAndCount" />
</template>

<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { FilterTableItem } from '@/types/components'
  import FilterTable from '@/components/TableFilter.vue'
  import ApplicationItem from '../components/applicationItem.vue'
  import StopApplicationOrder from '../components/stopApplicationOrder.vue'
  import SetPurchaseLabel from '../components/setPurchaseLabel.vue'
  import { Message } from '@arco-design/web-vue'
  import { findCompanyListByOutPurchase, findPurchasePlanItemPage, findPurchasePlanItemCountStatus, findPurchaseStatusPage, findPurchaseLabelPage } from '@/api/purchaseApplication'
  import useBaseDataStore from '@/store/modules/base-data'
  import { parseJson } from '@/utils'
  import { findSaasAndErpWarehouse } from '@/api/warehouse'

  onMounted(() => {
    getWareHouseList()
    getUserList()
    getListAndCount()
    getCompanyList()
    getLabelList()
    getPurchaseList()
  })

  const tabsList = [
    { key: 30, title: '待采购' },
    { key: 31, title: '采购中' },
    { key: 32, title: '待入库' },
    { key: 40, title: '已完成' },
  ]
  const filterItem = ref<Array<FilterTableItem>>([
    {
      type: 'input_keyword',
      key: 'billNos',
      keyItems: [{ label: '单号', value: 'billNos' }],
      keyWidth: '70',
      value: ref(),
      placeholder: '请输入',
      label: '',
      width: 160,
      isMultiple: true,
    },
    {
      type: 'input_keyword',
      key: 'skus',
      keyItems: [{ label: 'SKU', value: 'skus' }],
      keyWidth: '70',
      value: ref(),
      placeholder: '请输入',
      label: '',
      width: 160,
      isMultiple: true,
    },
    {
      key: 'warehouseCode',
      label: '收货仓',
      value: ref(),
      type: 'select',
      width: 120,
      optionItems: [],
    },
    {
      key: 'salesmanIds',
      label: '申购人',
      value: ref(),
      type: 'select_multiple',
      width: 120,
      optionItems: [],
    },
    {
      key: 'productType',
      label: '采购类型',
      value: ref(),
      type: 'select',
      width: 110,
      optionItems: [
        { label: '普货', value: 1 },
        { label: '样品', value: 2 },
      ],
    },
    {
      key: 'purchaseOrgIds',
      label: '采购公司',
      value: ref(),
      type: 'select_multiple',
      width: 160,
      optionItems: [
        { label: '采购公司1', value: '1' },
        { label: '采购公司2', value: '2' },
      ],
    },

    {
      type: 'keyword_date_range',
      key: 'gmtExpectDelivery',
      keyItems: [
        { label: '创建日期', value: 'gmtCreate' },
        { label: '期望交货日期', value: 'gmtExpectDelivery' },
      ],
      keyWidth: '130',
      value: ref(),
      placeholder: '请输入',
      label: '创建时间',
      width: 240,
      attrs: {
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        timePickerProps: { defaultValue: ['00:00:00', '23:59:59'] },
      },
    },
    {
      key: 'labels',
      label: '标签',
      value: ref(),
      type: 'select',
      width: 120,
      optionItems: [],
    },
    {
      key: 'purchaseStatus',
      label: '采购进度',
      value: ref(),
      type: 'select',
      width: 120,
      optionItems: [],
    },
  ])
  let searchVal = ref<any>({
    pageSize: 20,
    pageNum: 1,
    status: 30,
  })
  const currentTab = ref(30)
  const tableLoading = ref(false)
  const tableList = ref<Array<any>>([])
  const companyList = ref<Array<any>>([])
  const total = ref(0)
  const checkedList = ref<Array<any>>([])
  const showStopDialog = ref(false)
  const countMap = ref<any>({})
  const filterData = ref<any>({})
  const useBaseData = useBaseDataStore()
  const isCheckedAll = ref(false)
  const showSetLabel = ref(false)
  const currentList = ref<Array<any>>([])

  // 切换状态
  function changeStatus(status: number | string) {
    if (status === 100) return
    searchVal.value.status = status
    searchVal.value.pageNum = 1
    getTableList()
  }
  // 集团内子公司
  async function getCompanyList() {
    const res: any = await findCompanyListByOutPurchase()
    let list = res?.data || []
    filterItem.value[5].optionItems = list.map((el: any) => {
      return {
        label: el.companyName,
        value: el.id,
      }
    })
    companyList.value = list.map((el: any) => {
      return {
        purchaseOrgName: el.companyName,
        purchaseOrgId: el.id,
      }
    })
  }
  // 获取标签列表
  async function getLabelList() {
    const res: any = await findPurchaseLabelPage({
      pageSize: 500,
      pageNum: 1,
    })
    let list = res?.data?.records || []
    filterItem.value[7].optionItems = list.map((el: any) => {
      return {
        label: el.labelName,
        value: el.labelName,
      }
    })
  }
  // 获取采购进度列表
  async function getPurchaseList() {
    const res: any = await findPurchaseStatusPage({
      pageNum: 1,
      pageSize: 500,
    })
    let list = res?.data?.records || []
    filterItem.value[8].optionItems = list.map((el: any) => {
      return {
        label: el.purchaseStatus,
        value: el.purchaseStatus,
      }
    })
  }
  // 获取仓库列表
  async function getWareHouseList() {
    const res: any = await findSaasAndErpWarehouse()
    let list = res?.data || []
    filterItem.value[2].optionItems = list.map((el: any) => {
      return {
        label: el.warehouseName,
        value: el.warehouseCode,
      }
    })
  }
  // 获取所有用户列表
  async function getUserList() {
    await useBaseData.getUserList()
    filterItem.value[3].optionItems = useBaseData.userList.map((el: any) => {
      return {
        label: el.userName,
        value: el.id,
      }
    })
  }
  // 通过条件查询列表
  function searchByVal(info: any) {
    searchVal.value.pageNum = 1
    filterData.value = JSON.parse(JSON.stringify(info)) || {}
    getTableList()
  }
  // 分页
  function changePage(val: number) {
    searchVal.value.pageNum = val
    getTableList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getTableList()
  }

  // 查询列表和数量合计
  function getListAndCount() {
    getTableList()
    getCountList()
  }
  // 查询各状态下数量合计
  async function getCountList() {
    const res: any = await findPurchasePlanItemCountStatus()
    let counts = res?.data || []
    countMap.value = {}
    counts.forEach((el: any) => {
      countMap.value[el.status] = el.totalCount
    })
  }
  // 获取商品列表
  async function getTableList() {
    tableList.value = []
    checkedList.value = []
    isCheckedAll.value = false
    let params = {
      ...searchVal.value,
      ...filterData.value,
    }
    tableLoading.value = true
    const res: any = await findPurchasePlanItemPage(params)
    tableLoading.value = false
    let list = res?.data?.records || []

    list.forEach((item: any) => {
      let purchaseSpecs = item.purchaseSpecs ? parseJson(item.purchaseSpecs, {}) : {}
      item.purchaseSpecsArr = Object.values(purchaseSpecs)
    })
    tableList.value = list
    total.value = res?.data?.total || 0
  }

  // 终止
  function openStopDialog() {
    if (!checkedList.value.length) {
      Message.error('请选择单据')
      return
    }
    showStopDialog.value = true
  }
  // 选中
  function changeChecked(status: boolean, item: any) {
    if (status) {
      checkedList.value.push(item)
    } else {
      let index = checkedList.value.findIndex((el: any) => el.id == item.id)
      if (index > -1) {
        checkedList.value.splice(index, 1)
      }
    }
    isCheckedAll.value = checkedList.value.length == tableList.value.length
  }
  function changeCheckedAll(val: boolean) {
    tableList.value.forEach((item) => {
      item.isChecked = val
    })
    checkedList.value = val ? [...tableList.value] : []
  }
  // 设置标签
  function openSetLabel(list: Array<any>) {
    if (!list.length) {
      Message.error('请选择单据')
      return
    }
    currentList.value = list
    showSetLabel.value = true
  }
</script>
<style lang="less" scoped>
  :deep(.arco-tabs-nav-tab) {
    background-color: #fff;
  }
  .arco-scrollbar {
    height: 100%;
    overflow: hidden;
  }

  .order-item-wrap {
    display: flex;
    flex-wrap: wrap;
    padding-right: 10px;
    .order-item-w {
      width: 33.33%;
      min-width: 420px;
      padding: 4px;
    }
  }
</style>
